from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.activity.models import Gathering
from apps.activity.serializers import GatheringSerializer
from apps.users.models import User


class ActivityListView(APIView):
    '''显示所有活动'''

    def get(self, request):
        activity_all = Gathering.objects.all()
        serializer = GatheringSerializer(activity_all, many=True)
        count = Gathering.objects.all().count()
        data_list = []
        for data in serializer.data:
            data_dict = {
                'id': data['id'],
                'name': data['name'],
                'image': data['image'],
                'city': data['city'],
                'starttime': data['starttime'],
                'endrolltime': data['endrolltime'],
                'users': data['users']
            }
            data_list.append(data_dict)

        data = {
            'count': count,
            'next': '',
            'previous': '',
            'results': data_list
        }

        return Response(data)


class ActivityView(APIView):
    '''显示活动详情'''

    def get(self, request, id):
        spec = Gathering.objects.get(pk=id)
        serializer = GatheringSerializer(spec)
        user_list = []
        for user in spec.users.all():
            user_list.append(user)
        count = len(user_list)
        data = serializer.data
        data['users'] = count
        return Response(data)


class ActivityJoinView(CreateModelMixin,GenericAPIView):
    '''报名参加活动'''

    def post(self, request, id):
        user = request.user
        activity = Gathering.objects.get(pk=id)
        user = User.objects.get(username = user)
        users = activity.users.all()
        if user.is_authenticated:
            if user in users:
                activity.users.remove(user)
                return Response({
                    'message': '取消成功',
                    'success': True
                })
            else:
                activity.users.add(user)
                return Response({
                    'message': '报名成功',
                    'success': True
            })
        else:
                return Response({
                    'message': '操作失败请重新登录',
                    'success': False
                })
